package org.fall.srb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.fall.srb.common.exception.BusinessException;
import org.fall.srb.common.result.R;
import org.fall.srb.common.result.ResponseEnum;
import org.fall.srb.core.pojo.dto.ExcelDictDTO;
import org.fall.srb.core.pojo.entity.Dict;
import org.fall.srb.core.service.DictService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author sprogFall
 * @since 2021/7/13 22:52
 */
@Api(tags = "数据字典管理")
@RestController
@RequestMapping("/admin/core/dict")
@CrossOrigin
@Slf4j
public class AdminDictController {

    @Resource
    private DictService dictService;

    @ApiOperation("从Excel批量导入数据字典")
    @PostMapping("/import")
    public R batchImport(
            @ApiParam(value = "Excel文件")
            @RequestParam("file") MultipartFile file) {
        try {
            dictService.importData(file.getInputStream());
            return R.ok().message("批量导入成功");
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }
    }

    @ApiOperation("导出数据节点数据为excel并下载")
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode("myDict", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.exportData());
    }

    @ApiOperation("根据父节点id查看父节点下的子节点数据list")
    @GetMapping("/list/{parentId}")
    public R getDictListByParentId(
            @ApiParam("根据父节点id获取子节点的数据")
            @PathVariable("parentId") Long parentId) {
        List<Dict> list = dictService.getDictByParentId(parentId);
        return R.ok().data("list", list);
    }
}
